package cn.signalpha.modules.auth.endpoint;

import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.core.tool.api.R;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.enums.TicketType;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 令牌端点
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME)
@Api(value = "微信公众号", tags = "微信公众号")
public class WxMpEndPoint {

	private final WxMpService wxMpService;
	private final HttpServletResponse response;

	@GetMapping("/oauth/wechat/base")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "网页静默授权")
	public void oauthWeChatBase(@RequestParam(required = false) String state, @RequestParam String url) throws IOException {
		response.sendRedirect(wxMpService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, state));
	}

	@GetMapping("/oauth/wechat/userinfo")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "网页弹窗授权")
	public void oauthWeChat(@RequestParam(required = false) String state, @RequestParam String url) throws IOException {
		response.sendRedirect(wxMpService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, state));
	}

	@PostMapping("/oauth/wechat/js-signature")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "JsApi签名")
	public R oauthWeChatJsSignature(@RequestBody Map<String, Object> params) throws WxErrorException {
		return R.data(wxMpService.createJsapiSignature(String.valueOf(params.get("url"))));
	}

	@GetMapping("/oauth/wechat/js-ticket")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "JsTicket签名")
	public R oauthWeChatJsTicket() throws WxErrorException {
		return R.data(wxMpService.getTicket(TicketType.JSAPI));
	}
}
